package cn.yr.clock.handler;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信公众号
 */
@Component
@Slf4j
public class MpHandler {

    /**
     * 新增公众号菜单
     */
    private String addMenuUrl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=";

    /**
     * 获取access_token
     */
    private String getAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token";


    @Value("${mp.appId}")
    private String appId;

    @Value("${mp.secret}")
    private String secret;

    /**
     * 缓存器 默认90分后过期
     */
    private TimedCache<String, String> timedCache = CacheUtil.newTimedCache(1000*60*90);

    /**
     * 获取access_token
     * @return
     */
    public String getAccessToken(){
        String accessToken = timedCache.get("accessToken");
        if(StrUtil.isNotBlank(accessToken)){
            return accessToken;
        }
        MapBuilder<String, Object> builder = MapUtil.builder();
        Map<String, Object> map = builder.put("grant_type","client_credential")
                .put("appid", appId).put("secret", secret).map();
        String json = HttpUtil.get(getAccessTokenUrl, map);
        log.info("获取accessToken:{}",json);
        accessToken =  JSONUtil.parseObj(json).getStr("access_token");
        timedCache.put("accessToken",accessToken);
        return accessToken;
    }


    public void addMenu(){
        String accessToken = getAccessToken();
        MapBuilder<String, Object> builder = MapUtil.builder();
        Map<String, Object> map = builder.put("type","view")
                .put("name", "KEEP").put("url", "http://baidu.com").map();
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        list.add(map);
        HashMap<String, Object> body = MapUtil.newHashMap(1);
        body.put("button",list);
        String json = HttpUtil.post(addMenuUrl + accessToken, body);
        log.info("新增菜单:{}",json);
    }

}
